<?php

declare(strict_types=1);

namespace plugin\ycMassage\app\shop\middleware;

use Closure;
use plugin\ycMassage\app\model\MassageMch;
use plugin\ycMassage\app\model\MassageShop;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\State;
use support\Request;
use think\facade\Session;

/**
 * 应用后台权限中间件
 * @author 贵州猿创科技有限公司
 * @Email 416716328@qq.com
 * @DateTime 2023-03-11
 */
class AuthMiddleware
{
    /**
     * 中间件入口
     * @author 贵州猿创科技有限公司
     * @Email 416716328@qq.com
     * @DateTime 2023-03-11
     */
    public function handle(Request $request, Closure $next)
    {
        // 鉴权检测
        try {
            $this->canAccess($request);
            $response = $request->method() == 'OPTIONS' ? response('', 204) : $next($request);
        } catch (\Throwable $th) {
            $response = json(['code' => $th->getCode(), 'msg' => $th->getMessage(), 'file' => $th->getFile()]);
        }
        return $response;
    }

    /**
     * 业务逻辑
     * @author 贵州猿创科技有限公司
     * @Email 416716328@qq.com
     * @DateTime 2023-03-11
     */
    public function canAccess(Request $request): bool
    {
        # 无控制器地址
        if (!$request->control) {
            return true;
        }
        # 获取控制器鉴权信息
        $namespace = app()->getNamespace();
        $classNameSpace = "{$namespace}\\{$request->control}";
        $class = new \ReflectionClass($classNameSpace);
        $properties = $class->getDefaultProperties();
        # 无需登录方法
        $noNeedLogin = $properties['noNeedLogin'] ?? [];
        # 无需鉴权方法
        $noNeedAuth = $properties['noNeedAuth'] ?? [];
        # 无需验证APPID方法
        $noNeedAppid = $properties['noNeedAppid'] ?? [];
        # 设置全局Appid
        $request->appid = $request->header('Appid');
        if (!in_array($request->action(), $noNeedAppid)) {
            if (!$request->appid) {
                throw new \Exception('访问应用不存在', 404);
            }
        }
        # 不需要登录
        if (in_array($request->action(), $noNeedLogin)) {
            return true;
        }
        # 令牌验证
        $user = Session::get('ycMassage_shop');
        if (!$user) {
            throw new \Exception('登录已过期，请重新登录', 12000);
        }
        $request->user                  = $user;
        $request->uid                   = $user['id'];
        $request->saas_appid            = $user['saas_appid'];
        if (isset($user['use_mch_id'])) {
            $request->use_mch_id = $user['use_mch_id'];
        }
        if (isset($user['use_shop_id'])) {
            $request->use_shop_id = $user['use_shop_id'];
        }

        # 不需要鉴权
        if (in_array($request->action(), $noNeedAuth)) {
            return true;
        }
        if (!$request->use_mch_id && !$request->use_shop_id) {
            throw new \Exception('请选择管理角色', 400);
        }
        if ($request->use_mch_id) {
            $MassageMch = MassageMch::where(['uid' => $request->uid, 'id' => $request->use_mch_id, 'state' => State::YES['value'], 'examine' => Examine::YES['value']])->find();
            if (!$MassageMch) {
                throw new \Exception('商户不存在', 12000);
            }
        } else {
            $MassageShop = MassageShop::where(['uid' => $request->uid, 'id' => $request->use_shop_id, 'state' => State::YES['value'], 'examine' => Examine::YES['value']])->find();
            if (!$MassageShop) {
                throw new \Exception('门店不存在', 12000);
            }
        }
        return true;
    }
}
